﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class TCPManager : Singleton<TCPManager>
{
    private static byte[] result = new byte[1024];

    public static TcpListener server;
    public string ip;
    public int port=8000;
    public IPAddress[] ipAddress;
    public static List<TcpClient> clients = new List<TcpClient>();
    public IPAddress myIpAddress;
	void Start ()
    {
        ipAddress = Dns.GetHostAddresses(Dns.GetHostName());
        for (int i = 0; i < ipAddress.Length; i++)
        {
            if (ipAddress[i].AddressFamily == AddressFamily.InterNetwork)
            {
              string ip4 = ipAddress[i].ToString();  //ipv4
                if (ip4.Contains("192.168"))
                {
                    myIpAddress = ipAddress[i];
                    ip = ip4;
                }
            }
            else if (ipAddress[i].AddressFamily == AddressFamily.InterNetworkV6)
            {
                //ipv6 = ip.ToString(); //ipv6
            }
        }
        Debug.Log("本主机IP: " + ip);
        server = new TcpListener(myIpAddress, port);
        server.Start();
        server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server);
    }
    //异步回调方法
    private static void DoAcceptTcpclient(IAsyncResult ar)
    {
        // Get the listener that handles the client request.
        TcpListener listener = (TcpListener)ar.AsyncState;

        // End the operation and display the received data on 
        // the console.
        TcpClient client = listener.EndAcceptTcpClient(ar);

        clients.Add(client);

        // Process the connection here. (Add the client to a
        // server table, read data, etc.)
        Debug.LogFormat("Client connected completed,id:{0}",client.Client.RemoteEndPoint.ToString());
        //开启线程用来不断接收来自客户端的数据
        Thread t = new Thread(new ParameterizedThreadStart(ReceiveMessageFromClient));
        t.Start(client);

        server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server);

    }
    private static void ReceiveMessageFromClient(object reciveClient)
    {
        TcpClient client = reciveClient as TcpClient;
        if (client == null)
        {
            Debug.LogFormat("client error");
            return;
        }
        while (true)
        {
            try
            {
                NetworkStream stream = client.GetStream();
                Debug.LogFormat("waiting for data...");
                int num = stream.Read(result, 0, result.Length); //将数据读到result中                  
                if (num != 0)
                {
                    string str = Encoding.UTF8.GetString(result, 0, num);//只将流中读到的数据长度转换为字符串
                    Debug.LogFormat("数据长度：{0}，数据内容：{1}", num, str);
                }
                else
                {   //这里需要注意 当num=0时表明客户端已经断开连接，需要结束循环，不然会死循环一直卡住 
                    Debug.LogFormat("客户端关闭");
                    break;
                }
            }
            catch (Exception e)
            {
                clients.Remove(client);
                Debug.LogFormat("error:" + e.ToString());
                break;
            }

        }

    }

	void Update ()
    {
		
	}
}
